﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crude.Common;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Crude.Core
{
    public class ProjectObjectModelSaver
    {
        public void Save(string pomFilePath, ProjectObjectModel pom)
        {
            MemoryStream memoryStream = new MemoryStream();
            DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(ProjectObjectModel));
            dataContractSerializer.WriteObject(memoryStream, pom);

            memoryStream.Seek(0, SeekOrigin.Begin);

            StreamReader streamReader = new StreamReader(memoryStream);

            XmlDocument pomDoc = new XmlDocument();
            pomDoc.LoadXml(streamReader.ReadToEnd());


            //If file already exists - remove the read only attribute
            if (File.Exists(pomFilePath))
            {
                FileAttributes originalAttributes = File.GetAttributes(pomFilePath);
                FileAttributes readOnlyComplement = ~FileAttributes.ReadOnly;
                File.SetAttributes(pomFilePath, originalAttributes & readOnlyComplement);
            }


            XmlTextWriter xmlTextWriter = new XmlTextWriter(pomFilePath, null);
            xmlTextWriter.Formatting = Formatting.Indented;
            pomDoc.Save(xmlTextWriter);

            memoryStream.Close();
            xmlTextWriter.Close();
        }
    }
}
